package comtgl.demo.controller;

import comtgl.demo.dto.RateLimitDto;
import comtgl.demo.utils.RateLimitUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.function.Consumer;

@RestController
public class TestController {

    @Autowired
    private RateLimitUtils rateLimitUtils;

    @GetMapping("/api/test")
    public String test() throws InterruptedException {
        RateLimitDto rateLimit = new RateLimitDto();
        rateLimit.setLimitKey("test1");
        rateLimit.setSecondLimit(5);
        rateLimit.setMinuteLimit(10);
        for (int i = 0; i < 15; i++) {
//            if (!checkOK(rateLimit)) {
//                System.out.println(new Date() + "访问失败" + i);
//
//            } else {
//                run(rateLimit);
//                System.out.println(new Date() + "访问成功" + i);
//            }
            runLimitFun("test1", i, () -> createEvent());
        }
        return "test";
    }

    public static <T> void processWithConsumer(T value, Consumer<T> consumer) {
        consumer.accept(value);
    }

    public void runLimitFun(String key, int index, EventHandler handler) throws InterruptedException {
        RateLimitDto rateLimit = new RateLimitDto();
        rateLimit.setLimitKey(key);
        rateLimit.setSecondLimit(5);
        rateLimit.setMinuteLimit(10);
        if (rateLimitUtils.checkOK(rateLimit)) {
            rateLimitUtils.incrementCount(rateLimit.getLimitKey());
            System.out.println(new Date() + "可以访问" + index);
            //访问不同的函数
            handler.handle();

        } else {
            System.out.println(new Date() + "限制访问" + index);
            Thread.sleep(2000);
            runLimitFun(key, index, handler);
        }
    }


    public void createEvent() {
        try {
            Thread.sleep(2000);
            System.out.println("创建事件");
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}